﻿using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using KTD.Web.BaseDataAccessLayer;
using KTD.Web.Models;
using KTD.Web.Models.VD;
using Newtonsoft.Json;
using XXS.Common;
using XXS.Common.BaseDataAccessLayer;

namespace KTD.Web.BLL
{
    public class AuthorizeManager
    {
        private const string WeChatVerifyUrl =
                "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";

        private const string Key = "c0c03516ce596eb1830a6bc3554362c1";
        private const string AppId = "wx9cd89485273fb174";

        private readonly IBaseDAL<Member> _userDal;

        

        public AuthorizeManager()
        {
            _userDal = new BaseDAL<Member>(new DB());
        }

        public WeChatVerifyResultDto GetVerifyResult(WeChatAuthorizeDto im)
        {
            WebClient wc = new WebClient();

            var str = wc.DownloadString(WeChatVerifyUrl.ToFormat(AppId, Key, im.Code));

            return JsonConvert.DeserializeObject<WeChatVerifyResultDto>(str);
        }

        public bool Verify(WeChatAuthorizeDto im, out Member sysUser, out WeChatVerifyResultDto result)
        {
            var tmp = GetVerifyResult(im);

            result = tmp;

            sysUser = _userDal.Find(n => n.openid.Contains(tmp.OpenId));
            if (sysUser == null) {
                Member user = new Member() {
                    avatarUrl = im.avatarUrl,
                    wechaname = im.wechaname,
                    openid = tmp.OpenId
                };
                _userDal.Create(user);
            }

            return true;
        }

        public bool VerifyAndBind(string OpenId, Member sysUser, out string errorMsg)
        {
            errorMsg = string.Empty;
           
            sysUser.openid = OpenId;

            _userDal.Create(sysUser);

            return true;
            
        }

    }
}